import React, { useEffect } from "react";
import { Modal, Toast } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import $fetch from "../../../utils/app/$fetch";
import $getQuery from "../../../utils/app/$getQuery";

const TempPage = () => {
  const navigate: any = useNavigate();
  const $params: any = $getQuery();
  const outTradeNo = $params?.out_trade_no;
  let closeModal: any;

  useEffect(() => {
    initPage();
  }, []);

  const initPage = () => {
    const localoOutTradeNo = localStorage.getItem("localoOutTradeNo");
    if (localoOutTradeNo === outTradeNo) {
      Toast.show("请勿重复操作");
      return;
    } else {
      openModal(outTradeNo);
    }
  };
  const queryPayStatus = async (outTradeNo: any) => {
    try {
      const res: any = await $fetch(
        "/alipay/query",
        { outTradeNo },
        { loading: false }
      );
      if (res?.trade_status === "TRADE_SUCCESS") {
        // 支付成功
        if (res?.isNotStar === '0') {
          // 商城订单
          closeModal();
          localStorage.setItem("localoOutTradeNo", outTradeNo);
          window.location.replace("/#/order/list");
        } else if (res?.isNotStar === '1') {
          closeModal();
          localStorage.setItem("localoOutTradeNo", outTradeNo);
          window.location.replace("/#/club/success");
          // 会员订单
        }
      } else {
        // if (res?.isNotStar === '0') {
        //   // 商城订单
        //   closeModal();
        //   window.location.replace("/#/goods/list");
        // } else if (res?.isNotStar === '1') {
        //   // 会员订单
        //   // 商城订单
        //   closeModal();
        //   window.location.replace("/#/club/join");
        // }
        closeModal();
        window.location.replace("/#/home");
      }

      // if (res === "TRADE_SUCCESS") {
      //   closeModal();
      //   localStorage.setItem("localoOutTradeNo", outTradeNo);
      //   window.location.replace("/#/order/list");
      // } else {
      //   closeModal();
      //   window.location.replace("/#/goods/list");
      // }
    } catch (error) {
      closeModal();
      window.location.replace("/#/home");
      // window.location.replace("/#/goods/list");
    }
  };

  const handleClose = () => {
    closeModal();
    window.location.replace("/#/home");
  };

  const openModal = (outTradeNo: any) => {
    closeModal = Modal.show({
      content: "是否完成支付?",
      actions: [
        {
          key: "ok",
          text: "完成",
          primary: true,
          onClick: () => queryPayStatus(outTradeNo),
        },
        { key: "cancel", text: "未完成", onClick: () => handleClose() },
      ],
    }).close;
  };
  return <></>;
};

export default TempPage;
